package com.yonyou.cms.epc.service.graphic.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.cms.epc.client.entity.file.FilePO;
import com.yonyou.cms.epc.client.entity.graphic.GraphicAssemblyInfoEmp;
import com.yonyou.cms.epc.client.entity.graphic.GraphicAssemblyInfoPO;
import com.yonyou.cms.epc.client.entity.graphic.GraphicInfoPO;
import com.yonyou.cms.epc.mapper.file.FileMapper;
import com.yonyou.cms.epc.mapper.graphic.*;
import com.yonyou.cms.epc.service.graphic.GraphicAssemblyInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cms.epc.client.dto.graphic.GraphicAssemblyInfoDTO;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xh
 * @since 2022-06-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GraphicAssemblyInfoServiceImpl extends ServiceImpl<GraphicAssemblyInfoMapper, GraphicAssemblyInfoPO> implements GraphicAssemblyInfoService {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(GraphicAssemblyInfoServiceImpl.class);
    @Autowired
    GraphicAssemblyInfoMapper graphicAssemblyInfoMapper;
    @Autowired
    GraphicInfoMapper graphicInfoMapper;
    @Autowired
    GraphicSystemMapper graphicSystemMapper;
    @Autowired
    FileMapper fileMapper;
    @Autowired
    GradeInfoMapper gradeInfoMapper;
    @Autowired
    GraphicModelMapper graphicModelMapper;

    /**
     * 分页查询对应数据
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     * @author xh
     * @since 2022/6/21
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryCondition.put("appId", loginInfo.getAppId());
        page.setRecords(graphicAssemblyInfoMapper.selectPageBySql(page, queryCondition));
        return page;
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param queryCondition 查询条件
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author xh
     * @since 2022/6/21
     */
    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> selectListBySql(Map<String, Object> queryCondition) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryCondition.put("appId", loginInfo.getAppId());
        return graphicAssemblyInfoMapper.selectListBySql(queryCondition);
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param id 主键ID
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author xh
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getById(Integer id) {
        GraphicAssemblyInfoPO graphicAssemblyInfoPo = graphicAssemblyInfoMapper.selectById(id);
        if (graphicAssemblyInfoPo != null) {
            return graphicAssemblyInfoPo.toMaps();
        } else {
            throw new DALException("查询失败,没有符合条件的数据");
        }
    }

    /**
     * 根据DTO 进行数据新增
     *
     * @param graphicAssemblyInfoDTO 页面DTO
     * @return void
     * @author xh
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> insert(GraphicAssemblyInfoDTO graphicAssemblyInfoDTO) {
        //对对象进行赋值操作
        GraphicAssemblyInfoPO graphicAssemblyInfoPo = graphicAssemblyInfoDTO.transDtoToPo(GraphicAssemblyInfoPO.class);
        //执行插入
        graphicAssemblyInfoMapper.insert(graphicAssemblyInfoPo);
        //返回插入的值
        return graphicAssemblyInfoMapper.selectById(graphicAssemblyInfoPo.getAssemblyId()).toMaps();
    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param graphicAssemblyInfoDTO 页面DTO
     * @return void
     * @author xh
     * @since 2022/6/21
     */
    @Override
    public Map<String, Object> update(GraphicAssemblyInfoDTO graphicAssemblyInfoDTO) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        // 查询当前登录用户ID
        Long userId = graphicAssemblyInfoDTO.getUserId();
        //图解主表维护
        List<Map<String, Object>> parentList = null;
        Integer graphicId = graphicAssemblyInfoDTO.getGraphicId();
        GraphicInfoPO graphicInfoPo = graphicInfoMapper.selectById(graphicId);
        if (graphicInfoPo != null) {
            //修改
//            graphicInfoPO.setSystemCode(graphicAssemblyInfoDTO.getSystemCode());
//            graphicInfoPO.setSystemName(graphicAssemblyInfoDTO.getSystemName());
//            graphicInfoPO.setModelCode(graphicAssemblyInfoDTO.getModelCode());
//            graphicInfoPO.setModelName(graphicAssemblyInfoDTO.getModelName());
            graphicInfoPo.setOkstate(graphicAssemblyInfoDTO.getOkstate());
            graphicInfoPo.setRemark(graphicAssemblyInfoDTO.getRemark());
            graphicInfoPo.setUpdatedAt(now);
            graphicInfoPo.setUpdatedBy(loginInfo.getUserId().toString());
            graphicInfoMapper.updateById(graphicInfoPo);
        } else {
            //新增,判断代码和名称是否重复
            Map<String, Object> queryCondition = new HashMap();
            queryCondition.put("modelCode", graphicAssemblyInfoDTO.getModelCode());
            queryCondition.put("systemCode", graphicAssemblyInfoDTO.getSystemCode());
            queryCondition.put("appId", loginInfo.getAppId());
            parentList = graphicInfoMapper.selectListBySql(queryCondition);
            if (parentList.size() > 0) {
                throw new DALException("添加失败,车型对应的系统已存在");
            }
            GraphicInfoPO graphicInfo = graphicAssemblyInfoDTO.transDtoToPo(GraphicInfoPO.class);
            graphicInfoMapper.insert(graphicInfo);
            return graphicInfo.toMaps();
        }

        return graphicInfoPo.toMaps();
    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param graphicAssemblyInfoDTO 页面DTO
     * @return void
     * @author xh
     * @since 2022/6/21
     */
    @Override
    public Map<String, Object> updateAppintmentInfo(GraphicAssemblyInfoDTO graphicAssemblyInfoDTO) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        // 查询当前登录用户ID
        Long userId = graphicAssemblyInfoDTO.getUserId();
        //图解子表维护
        Integer assemblyId = graphicAssemblyInfoDTO.getAssemblyId();
        GraphicAssemblyInfoPO graphicAssemblyInfoPo = graphicAssemblyInfoMapper.selectById(assemblyId);
        List<Map<String, Object>> partList=null;
        boolean isPart = true;
//        if(graphicAssemblyInfoPo!=null) {
//            if (!graphicAssemblyInfoPo.getRecordVersion().equals(graphicAssemblyInfoDTO.getRecordVersion())) {
//                throw new ServiceBizException("存在同步操作,请关闭后重试");
//            }
//        }

        if (!"0".equals(graphicAssemblyInfoDTO.getOneMenu())) {
            //校验备件是否存在
            Map<String, Object> queryCondition2 = new HashMap<>();
            queryCondition2.put("appId", loginInfo.getAppId());
            queryCondition2.put("bjxmbh", graphicAssemblyInfoDTO.getGraphicCode());
            queryCondition2.put("bjzwmc", graphicAssemblyInfoDTO.getGraphicName());
            partList = graphicAssemblyInfoMapper.selectPartListBySql(queryCondition2);
            if (partList.size() == 0) {
                throw new DALException("添加失败,备件代码或名称不存在");
            }
        }
        if (graphicAssemblyInfoPo != null) {
            //修改
            graphicAssemblyInfoPo.setRedianCode(graphicAssemblyInfoDTO.getRedianCode());
            graphicAssemblyInfoPo.setGraphicCode(graphicAssemblyInfoDTO.getGraphicCode());
            graphicAssemblyInfoPo.setGraphicName(graphicAssemblyInfoDTO.getGraphicName());
            graphicAssemblyInfoPo.setThreeMenu(graphicAssemblyInfoDTO.getThreeMenu());
            graphicAssemblyInfoPo.setTwoMenu(graphicAssemblyInfoDTO.getTwoMenu());
            graphicAssemblyInfoPo.setOneMenu(graphicAssemblyInfoDTO.getOneMenu());
            graphicAssemblyInfoPo.setUnitAmount(graphicAssemblyInfoDTO.getUnitAmount());
            graphicAssemblyInfoPo.setRemarkAssembly(graphicAssemblyInfoDTO.getRemarkAssembly());
            graphicAssemblyInfoPo.setUpdatedAt(now);
            graphicAssemblyInfoPo.setUpdatedBy(loginInfo.getUserId().toString());
            graphicAssemblyInfoPo.setIsSpare(graphicAssemblyInfoDTO.getIsSpare());
            graphicAssemblyInfoMapper.updateById(graphicAssemblyInfoPo);

            // 保存上传的图片
            if (graphicAssemblyInfoDTO.getPicFiles().size() > 0) {
                for (FilePO newFile : graphicAssemblyInfoDTO.getPicFiles()) {
                    // 无id则为新上传文件
                    if (newFile.getId() == null) {
                        newFile.setXtfjlx("tt_graphic_assembly_info");
                        newFile.setXtdjid(graphicAssemblyInfoPo.getAssemblyId().longValue());
                        newFile.setCreatedBy(userId.toString());
                        newFile.setCreatedAt(LocalDateTime.now());
                        newFile.setAppId(loginInfo.getAppId());
                        fileMapper.insert(newFile);
                    }
                }
            }
            return graphicAssemblyInfoPo.toMaps();
        } else {
            if (!"0".equals(graphicAssemblyInfoDTO.getOneMenu())) {
                //是否重复备件
//                Map<String, Object> queryCondition3 = new HashMap();
//                queryCondition3.put("modelCode", graphicAssemblyInfoDTO.getModelCode());
//                queryCondition3.put("systemCode", graphicAssemblyInfoDTO.getSystemCode());
//                queryCondition3.put("graphicCode", graphicAssemblyInfoDTO.getGraphicCode());
//                queryCondition3.put("redianCode", graphicAssemblyInfoDTO.getRedianCode());
//                queryCondition3.put("oneMenu", graphicAssemblyInfoDTO.getOneMenu());
//                queryCondition3.put("appId", loginInfo.getAppId());
//                List<Map<String, Object>> parentList3 = graphicAssemblyInfoMapper.selectListBySql(queryCondition3);
//                if (parentList3.size() > 0) {
//                    throw new DALException("备件信息已保存,请勿重复添加！");
//                }
            } else {
                //是否重复总成
                Map<String, Object> queryCondition2 = new HashMap();
                queryCondition2.put("modelCode", graphicAssemblyInfoDTO.getModelCode());
                queryCondition2.put("systemCode", graphicAssemblyInfoDTO.getSystemCode());
                queryCondition2.put("graphicCode", graphicAssemblyInfoDTO.getGraphicCode());
                queryCondition2.put("appId", loginInfo.getAppId());
                List<Map<String, Object>> parentList2 = graphicAssemblyInfoMapper.selectListBySql(queryCondition2);
                if (parentList2.size() > 0) {
                    throw new DALException("总成信息已保存,请勿重复添加！");
                }
            }

            //新增
            GraphicAssemblyInfoPO graphicAssemblyInfoPoInsert = new GraphicAssemblyInfoPO();
            graphicAssemblyInfoPoInsert.setGraphicId(graphicAssemblyInfoDTO.getGraphicId());
            graphicAssemblyInfoPoInsert.setSystemCode(graphicAssemblyInfoDTO.getSystemCode());
            graphicAssemblyInfoPoInsert.setModelCode(graphicAssemblyInfoDTO.getModelCode());
            graphicAssemblyInfoPoInsert.setRedianCode(graphicAssemblyInfoDTO.getRedianCode());
            graphicAssemblyInfoPoInsert.setGraphicCode(graphicAssemblyInfoDTO.getGraphicCode());
            graphicAssemblyInfoPoInsert.setGraphicName(graphicAssemblyInfoDTO.getGraphicName());
            graphicAssemblyInfoPoInsert.setThreeMenu(graphicAssemblyInfoDTO.getThreeMenu());
            graphicAssemblyInfoPoInsert.setTwoMenu(graphicAssemblyInfoDTO.getTwoMenu());
            if (graphicAssemblyInfoDTO.getOneMenu() != null && graphicAssemblyInfoDTO.getOneMenu() != "") {
                graphicAssemblyInfoPoInsert.setOneMenu(graphicAssemblyInfoDTO.getOneMenu());
            } else {
                graphicAssemblyInfoPoInsert.setOneMenu("0");
            }
            graphicAssemblyInfoPoInsert.setUnitAmount(graphicAssemblyInfoDTO.getUnitAmount());
            graphicAssemblyInfoPoInsert.setRemarkAssembly(graphicAssemblyInfoDTO.getRemarkAssembly());
            graphicAssemblyInfoPoInsert.setIsSpare(graphicAssemblyInfoDTO.getIsSpare());
            //赋partId给查看备件图片
            if(partList!=null){
                graphicAssemblyInfoPoInsert.setPartId(partList.get(0).get("id").toString());
            }
            graphicAssemblyInfoMapper.insert(graphicAssemblyInfoPoInsert);
            // 保存上传的图片
            if (graphicAssemblyInfoDTO.getPicFiles().size() > 0) {
                for (FilePO newFile : graphicAssemblyInfoDTO.getPicFiles()) {
                    // 无id则为新上传文件
                    if (newFile.getId() == null) {
                        newFile.setXtfjlx("tt_graphic_assembly_info");
                        newFile.setXtdjid(graphicAssemblyInfoPoInsert.getAssemblyId().longValue());
                        newFile.setCreatedBy(userId.toString());
                        newFile.setCreatedAt(LocalDateTime.now());
                        newFile.setAppId(loginInfo.getAppId());
                        fileMapper.insert(newFile);
                    }
                }
            }
            return graphicAssemblyInfoPoInsert.toMaps();
        }
    }

    /**
     * 根据ID 进行删除数据
     *
     * @param id
     * @return void
     * @author xh
     * @since 2022/6/21
     */
    @Override
    public void deleteById(Integer id) {
        boolean deleteCount = graphicAssemblyInfoMapper.deleteBatch(id);
        logger.debug("删除数量：{}", deleteCount);
        if (!deleteCount) {
            throw new DALException("删除失败,没有符合条件的数据");
        } else {
            gradeInfoMapper.deleteAssemblyId(id);
        }
    }

    /**
     * 根据ids 进行删除
     *
     * @param ids
     * @return void
     * @author xh
     * @since 2022/6/21
     */
    @Override
    public void deleteBatchIds(String ids) {
        List<Integer> longList = StringUtils.convertStrToArray(ids, ",", Integer.class);
        int deleteCount = graphicAssemblyInfoMapper.deleteBatchIds(longList);
        logger.debug("删除数量：{}", deleteCount);
        if (deleteCount != longList.size()) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

    /**
     * 批量导入
     *
     * @param datas
     * @return Map
     * @author xh
     * @since 2022/6/21
     */
    @Override
    public Map<String, Object> imports(List<Map<String, Object>> datas) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<GraphicInfoPO> graphicInfoPoList = new ArrayList<>();
        List<GraphicAssemblyInfoPO> graphicAssemblyInfoPoList = new ArrayList<>();
        long b1= System.currentTimeMillis();
        //导入之前校验
        List<Map<String, Object>> errorData = this.importsChecking(datas);
        logger.info("結束-----------------------------------车型系统效验时间"+(System.currentTimeMillis() - b1));
        if (errorData.size() > 0) {
            return new HashMap<String, Object>() {{
                put("status", false);
                put("errorData", errorData);
            }};
        } else {
            long b2= System.currentTimeMillis();
            for (int i = 0; i < datas.size(); i++) {
                int rownum = i + 2;
                //主表
                Map<String, Object> row = datas.get(i);
                //不存在，就存入集合做批量新增操作
                GraphicInfoPO graphicInfoPo = new GraphicInfoPO();
                graphicInfoPo.setModelCode(row.get("modelCode").toString().trim());
                graphicInfoPo.setModelName(row.get("modelName").toString().trim());
                graphicInfoPo.setSystemCode(row.get("systemCode").toString().trim());
                graphicInfoPo.setSystemName(row.get("systemName").toString().trim());
                graphicInfoPo.setOkstate(30421002);//默认未完成
                graphicInfoPo.setIsDeleted(0);
                graphicInfoPo.setRecordVersion(1);
                graphicInfoPo.setRemark(row.get("remarkAssembly").toString().trim());
                graphicInfoPo.setAppId(loginInfo.getAppId());
                graphicInfoPo.setOwnerParCode(loginInfo.getOwnerParCode());
                graphicInfoPo.setOwnerCode(loginInfo.getOwnerCode());
                graphicInfoPo.setOrgId(loginInfo.getOrgId().toString());
                graphicInfoPo.setCompanyCode(loginInfo.getCompanyCode());
                graphicInfoPo.setCreatedBy(loginInfo.getUserId().toString());
                graphicInfoPo.setUpdatedBy(loginInfo.getUserId().toString());
                graphicInfoPo.setCreatedAt(LocalDateTime.now());
                graphicInfoPo.setUpdatedAt(LocalDateTime.now());
                graphicInfoPoList.add(graphicInfoPo);
                //新增子表备件
                GraphicAssemblyInfoPO graphicAssemblyInfoPo = new GraphicAssemblyInfoPO();
                graphicAssemblyInfoPo.setModelCode(row.get("modelCode").toString().trim());
                graphicAssemblyInfoPo.setSystemCode(row.get("systemCode").toString().trim());
                graphicAssemblyInfoPo.setRedianCode(row.get("redianCode").toString().trim());
                graphicAssemblyInfoPo.setGraphicCode(row.get("graphicCode").toString().trim());
                graphicAssemblyInfoPo.setGraphicName(row.get("graphicName").toString().trim());
                if (row.get("oneMenu").toString().trim() != null && row.get("oneMenu").toString().trim() != "") {
                    graphicAssemblyInfoPo.setOneMenu(row.get("oneMenu").toString().trim());
                } else {
                    graphicAssemblyInfoPo.setOneMenu("0");
                }
                graphicAssemblyInfoPo.setUnitAmount(row.get("unitAmount").toString().trim());
                graphicAssemblyInfoPo.setRemarkAssembly(row.get("remarkAssembly").toString().trim());
                graphicAssemblyInfoPo.setAppId(loginInfo.getAppId());
                graphicAssemblyInfoPo.setIsDeleted(0);
                graphicAssemblyInfoPo.setRecordVersion(1);
                graphicAssemblyInfoPo.setOwnerParCode(loginInfo.getOwnerParCode());
                graphicAssemblyInfoPo.setOwnerCode(loginInfo.getOwnerCode());
                graphicAssemblyInfoPo.setOrgId(loginInfo.getOrgId().toString());
                graphicAssemblyInfoPo.setCompanyCode(loginInfo.getCompanyCode());
                graphicAssemblyInfoPo.setCreatedBy(loginInfo.getUserId().toString());
                graphicAssemblyInfoPo.setUpdatedBy(loginInfo.getUserId().toString());
                graphicAssemblyInfoPo.setCreatedAt(LocalDateTime.now());
                graphicAssemblyInfoPo.setUpdatedAt(LocalDateTime.now());
                graphicAssemblyInfoPo.setAppId(loginInfo.getAppId());
                graphicAssemblyInfoPo.setRownum(rownum);
                //初始化是否备件字段，当有上级代码就是选中
                if (row.get("oneMenu").toString() != null && row.get("oneMenu").toString() != "") {
                    graphicAssemblyInfoPo.setIsSpare(10041001);
                } else {
                    graphicAssemblyInfoPo.setIsSpare(10041002);
                }
                graphicAssemblyInfoPoList.add(graphicAssemblyInfoPo);
            }
            //校验备件：查询所有备件，开始校验
            Map<String, Object> queryCondition3 = new HashMap<>();
            queryCondition3.put("appId", loginInfo.getAppId());
            List<Map<String, Object>> partList = graphicAssemblyInfoMapper.selectNotPartListBySql(queryCondition3,graphicAssemblyInfoPoList);
            for (Map<String, Object> partMap : partList){
                errorData.add(new HashMap<String, Object>() {{
                    put("rownum", partMap.get("ROWNUM"));
                    put("errormsg", "备件代码不存在，导入失败！");
                }});
            }
            if (errorData.size() > 0) {
                return new HashMap<String, Object>() {{
                    put("status", false);
                    put("errorData", errorData);
                }};
            }
            logger.info("結束-----------------------------------检验备件代码不存在"+(System.currentTimeMillis() - b2));
            List<GraphicInfoPO> graphicInfoPoListRemoval = null;
            long b3= System.currentTimeMillis();
            if (graphicInfoPoList.size() > 0) {
                //去重
                graphicInfoPoListRemoval = graphicInfoPoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>
                        (Comparator.comparing(o -> o.getSystemCode() + ";" + o.getModelCode()))), ArrayList::new));

                //批量删除子表-添加前操作
                graphicInfoMapper.deleteBatchModelSystem(graphicInfoPoListRemoval);
                //批量新增主表
                graphicInfoMapper.insertBatch(graphicInfoPoListRemoval);
            }
            logger.info("結束-----------------------------------删除和插入主表数据时间"+(System.currentTimeMillis() - b3));
            if (graphicAssemblyInfoPoList.size() > 0) {
                List<GraphicAssemblyInfoPO> graphicAssemblyInfoPoListRemoval = null;
                //去重
                graphicAssemblyInfoPoListRemoval = graphicAssemblyInfoPoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>
                        (Comparator.comparing(o -> o.getSystemCode() + ";" + o.getModelCode()))), ArrayList::new));
                long b4= System.currentTimeMillis();
                //批量删除子表-添加前操作
                graphicAssemblyInfoMapper.deleteBatchModelSystem(graphicAssemblyInfoPoListRemoval);
                //批量新增子表
                graphicAssemblyInfoMapper.insertBatch(graphicAssemblyInfoPoList);
                logger.info("結束-----------------------------------删除和插入子表数据时间"+(System.currentTimeMillis() - b4));
                for (int i = 0; i < graphicInfoPoListRemoval.size(); i++) {
                    //批量更新子表图解ID
                    GraphicAssemblyInfoPO graphicAssemblyinfoPo = new GraphicAssemblyInfoPO();
                    graphicAssemblyinfoPo.setGraphicId(graphicInfoPoListRemoval.get(i).getGraphicId());
                    graphicAssemblyinfoPo.setModelCode(graphicInfoPoListRemoval.get(i).getModelCode());
                    graphicAssemblyinfoPo.setSystemCode(graphicInfoPoListRemoval.get(i).getSystemCode());
                    graphicAssemblyInfoMapper.updateGraphicIds(graphicAssemblyinfoPo);
                }
            }
            return new HashMap<String, Object>() {{
                put("status", true);
            }};
        }

    }

    /**
     * <p>
     * 查询图片服务类
     * </p>
     *
     * @author xh
     * @since 2022-06-09
     */
    @Override
    public List<Map<String, Object>> getfilelist(Map<String, Object> map) {
        if (map.get("xtdjid") == null) {
            map.put("xtdjid", -1);
        }
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        map.put("appId", loginInfo.getAppId());
        List<Map<String, Object>> maps = fileMapper.selectFilesByDjid(map);
        return maps;
    }

    /**
     * 删除图片文件
     *
     * @param map
     * @author xuhang
     * @since 2022-06-30
     */
    @Override
    @Transactional
    public int deleteZcPicFile(Map<String, Long> map) {
        int result = fileMapper.deleteById(map.get("id"));
        return result;
    }

    /**
     * 分页查询图解物料数据
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     * @author xh
     * @since 2022/6/30
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectgraphicAndAssemblyInfoPage(Page page, Map<String, Object> queryCondition) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryCondition.put("appId", loginInfo.getAppId());
        page.setRecords(graphicAssemblyInfoMapper.selectgraphicAndAssemblyInfoPage(page, queryCondition));
        return page;
    }

    /**
     * 分页查询备件信息
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     * @author xh
     * @since 2022/7/07
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectpartinfoPage(Page page, Map<String, Object> queryCondition) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryCondition.put("appId", loginInfo.getAppId());
        page.setRecords(graphicAssemblyInfoMapper.selectpartinfoPage(page, queryCondition));
        return page;
    }

    //导入功能前校验车型和系统
    public List<Map<String, Object>> importsChecking(List<Map<String, Object>> datas) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<Map<String, Object>> errorData = new ArrayList<>();
        Map<String, Object> queryCondition = new HashMap<>();
        queryCondition.put("appId", loginInfo.getAppId());
        queryCondition.put("statu", 30411001);
        //查询系统是否已停用
        List<Map<String, Object>> systemList = graphicSystemMapper.selectListBySql(queryCondition);
        //查询车型是否存在
        Map<String, Object> queryCondition2 = new HashMap<>();
        queryCondition2.put("appId", loginInfo.getAppId());
        List<Map<String, Object>> modelList = graphicModelMapper.selectListBySql(queryCondition2);
        for (int i = 0; i < datas.size(); i++) {
            Map<String, Object> row = datas.get(i);
            boolean isSystem = true;
            boolean isModel = true;
            int rownum = i + 2;
            for (int j = 0; j < systemList.size() ; j++) {
                if (row.get("systemCode").toString().trim().equals(systemList.get(j).get("systemCode").toString())
                        && row.get("systemName").toString().trim().equals(systemList.get(j).get("systemName").toString())) {
                    isSystem = false;
                    break;
                }
            }
            if (isSystem) {
                errorData.add(new HashMap<String, Object>() {{
                    put("rownum", rownum);
                    put("errormsg", "导入的系统编号或名称不存在或已停用，导入失败！");
                }});
                continue;
            }
            for (int k = 0; k < modelList.size() ; k++) {
                if (row.get("modelCode").toString().trim().equals(modelList.get(k).get("modelCode").toString())
                        && row.get("modelName").toString().trim().equals(modelList.get(k).get("modelName").toString())) {
                    isModel = false;
                    break;
                }
            }
            if (isModel) {
                errorData.add(new HashMap<String, Object>() {{
                    put("rownum", rownum);
                    put("errormsg", "导入的车型编号或名称不存在，导入失败！");
                }});
                continue;
            }
        }
        return errorData;
    }

    /**
     * 批量导入
     *
     * @param datas
     * @return Map
     * @author xh
     * @since 2022/7/25
     */
    @Override
    public Map<String, Object> importsUpgrade(List<Map<String, Object>> datas) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<GraphicAssemblyInfoEmp> graphicAssemblyInEmpList = new ArrayList<>();
        long b1= System.currentTimeMillis();
        //导入之前校验车型和系统
        List<Map<String, Object>> errorData = this.importsChecking(datas);
        logger.info("結束-----------------------------------车型系统效验时间"+(System.currentTimeMillis() - b1));
        if (errorData.size() > 0) {
            return new HashMap<String, Object>() {{
                put("status", false);
                put("errorData", errorData);
            }};
        } else {

            for (int i = 0; i < datas.size(); i++) {
                int rownum = i + 2;
                //主表
                Map<String, Object> row = datas.get(i);
                //不存在，就存入集合做批量新增操作
                GraphicAssemblyInfoEmp graphicAssemblyInfoEmp = new GraphicAssemblyInfoEmp();
                graphicAssemblyInfoEmp.setModelCode(row.get("modelCode").toString().trim());
                graphicAssemblyInfoEmp.setModelName(row.get("modelName").toString().trim());
                graphicAssemblyInfoEmp.setSystemCode(row.get("systemCode").toString().trim());
                graphicAssemblyInfoEmp.setSystemName(row.get("systemName").toString().trim());
                graphicAssemblyInfoEmp.setOkstate(30421002);//默认未完成
                //新增子表备件
                graphicAssemblyInfoEmp.setRedianCode(row.get("redianCode").toString().trim());
                graphicAssemblyInfoEmp.setGraphicCode(row.get("graphicCode").toString().trim());
                graphicAssemblyInfoEmp.setGraphicName(row.get("graphicName").toString().trim());
                if (row.get("oneMenu").toString().trim() != null && row.get("oneMenu").toString().trim() != "") {
                    graphicAssemblyInfoEmp.setOneMenu(row.get("oneMenu").toString().trim());
                } else {
                    graphicAssemblyInfoEmp.setOneMenu("0");
                }
                graphicAssemblyInfoEmp.setUnitAmount(row.get("unitAmount").toString().trim());
                graphicAssemblyInfoEmp.setRemarkAssembly(row.get("remarkAssembly").toString().trim());
                graphicAssemblyInfoEmp.setAppId(loginInfo.getAppId());
                graphicAssemblyInfoEmp.setIsDeleted(0);
                graphicAssemblyInfoEmp.setRecordVersion(1);
                graphicAssemblyInfoEmp.setOwnerParCode(loginInfo.getOwnerParCode());
                graphicAssemblyInfoEmp.setOwnerCode(loginInfo.getOwnerCode());
                graphicAssemblyInfoEmp.setOrgId(loginInfo.getOrgId().toString());
                graphicAssemblyInfoEmp.setCompanyCode(loginInfo.getCompanyCode());
                graphicAssemblyInfoEmp.setCreatedBy(loginInfo.getUserId().toString());
                graphicAssemblyInfoEmp.setUpdatedBy(loginInfo.getUserId().toString());
                graphicAssemblyInfoEmp.setCreatedAt(LocalDateTime.now());
                graphicAssemblyInfoEmp.setUpdatedAt(LocalDateTime.now());
                graphicAssemblyInfoEmp.setAppId(loginInfo.getAppId());
                graphicAssemblyInfoEmp.setErrorRow(rownum);
                //初始化是否备件字段，当有上级代码就是选中
                if (row.get("oneMenu").toString() != null && row.get("oneMenu").toString() != "") {
                    graphicAssemblyInfoEmp.setIsSpare(10041001);
                } else {
                    graphicAssemblyInfoEmp.setIsSpare(10041002);
                }
                graphicAssemblyInEmpList.add(graphicAssemblyInfoEmp);
            }
            if (graphicAssemblyInEmpList.size() > 0) {
                long b8= System.currentTimeMillis();
                //批量删除创建人的临时表数据
                graphicAssemblyInfoMapper.deleteBatchEmp(loginInfo.getUserId());
                logger.info("結束-----------------------------------临时表删除时间"+(System.currentTimeMillis() - b8));
                long b2= System.currentTimeMillis();
                //批量新增临时表
                graphicAssemblyInfoMapper.insertBatchEmp(graphicAssemblyInEmpList);
                logger.info("結束-----------------------------------临时表插入时间"+(System.currentTimeMillis() - b2));
            }
            long b3= System.currentTimeMillis();
            //更新校验错误字段
            graphicAssemblyInfoMapper.updateNotPartList();
            //校验备件是否存在
            List<GraphicAssemblyInfoEmp> empList=graphicAssemblyInfoMapper.selectEmp();
            if(empList.size()>0){
                for (GraphicAssemblyInfoEmp empMap : empList){
                    errorData.add(new HashMap<String, Object>() {{
                        put("rownum", empMap.getErrorRow());
                        put("errormsg", empMap.getError()+"，导入失败！");
                    }});
                }
                if (errorData.size() > 0) {
                    return new HashMap<String, Object>() {{
                        put("status", false);
                        put("errorData", errorData);
                    }};
                }
                logger.info("結束-----------------------------------备件是否存在效验时间"+(System.currentTimeMillis() - b3));
            }else{//校验成功
                long b4= System.currentTimeMillis();
                List<GraphicAssemblyInfoEmp> graphicInfoPoListRemoval = null;
                    //去重
                    graphicInfoPoListRemoval = graphicAssemblyInEmpList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>
                            (Comparator.comparing(o -> o.getSystemCode() + ";" + o.getModelCode()))), ArrayList::new));

                //批量删除子表-添加前操作
                graphicInfoMapper.deleteBatchModelSystemEmp(graphicInfoPoListRemoval);
                //批量新增主表
                graphicInfoMapper.insertInFo(loginInfo.getUserId().toString()); //插入主表数据
                logger.info("結束-----------------------------------主表插入时间"+(System.currentTimeMillis() - b4));
                long b5= System.currentTimeMillis();
                //批量删除子表-添加前操作
                graphicAssemblyInfoMapper.deleteBatchModelSystemEmp(graphicInfoPoListRemoval);
                //批量新增子表
                graphicAssemblyInfoMapper.insertAssembly(loginInfo.getUserId().toString());//插入子表数据
                logger.info("結束-----------------------------------子表插入时间"+(System.currentTimeMillis() - b5));
            }
            return new HashMap<String, Object>() {{
                put("status", true);
            }};
        }

    }

}